package com.lsj.core.response;

import com.alibaba.fastjson.annotation.JSONField;
import com.lsj.core.exception.CustomerException;
import lombok.Data;

import java.util.Date;

@Data
public  class  CommonResult<T> {
    private int code;
    private String message;
    private T data;
    @JSONField(format = "yyyy-MM-dd HH:mm:ss")
    private Date timestamp;

    public CommonResult(int code,T data,String msg) {
        this.code = code;
        this.data = data;
        this.message = msg;
        this.timestamp = new Date();
    }



    public static <T> CommonResult success(T data){
        return  new CommonResult<T>(ResponseType.success.getCode(), data, null);
    };
    public static  <T> CommonResult success(){
        return new CommonResult<T>(ResponseType.success.getCode(),null,null);
    };

    public static  <T> CommonResult error(CustomerException e){
        return new CommonResult<T>(e.getCode(),null,e.getMessage());
    }
    public static  <T> CommonResult error(String msg){
        return new CommonResult<T>(ResponseType.error.getCode(),null,msg);
    }
    public static <T> CommonResult error(T data, String msg){
        return   new CommonResult<T>(ResponseType.error.getCode(),data,msg);
    }


    public static void checkIsOk(CommonResult result){
        if(ResponseType.success.getCode() != result.getCode()){
            throw new CustomerException(ResponseType.system_error,result.getMessage());
        }
    }
}
